/*
 * @描述: 全局获取用户信息以及权限模块
 * @Author: /songzi
 * @Date: 2020-03-16 15:06:44
 * @Last Modified by: songzi
 * @Last Modified time: 2020-03-26 14:44:13
 */
/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */

import React, { useState, Fragment } from 'react';
import { Spin } from 'antd';
import { connect } from 'dva';
import styles from './userInfoLayout.less';

/**
 * use Authorized check all menu item
 */
const LayoutLoading = props => (
  <div className={styles.contentLoading}>
    <div className="page-loading-warp">
      {/* <div className="ant-spin ant-spin-lg ant-spin-spinning">
        <span className="ant-spin-dot ant-spin-dot-spin">
          <i className="ant-spin-dot-item"></i>
          <i className="ant-spin-dot-item"></i>
          <i className="ant-spin-dot-item"></i>
          <i className="ant-spin-dot-item"></i>
        </span>
      </div> */}
      <Spin size="large" tip={props.tip}></Spin>
    </div>
  </div>
);

const UserInfoLayout = props => {
  const { dispatch, children, login, autoLogining, currentLoading, fetchPermissionsLoading, authApisLoading } = props;
  const updateUserInfo = ({ userId, accessToken }) => {
    if (dispatch && accessToken && userId) {
      // 获取用户信息
      dispatch({
        type: 'user/fetchCurrent',
        payload: { userId }
      });
      // 获取用户权限
      dispatch({
        type: 'user/fetchPermissions',
        payload: { userId }
      });
    }
  };

  useState(async () => {
    let token = { ...login };
    if (!token.userId || !token.accessToken) {
      token = await dispatch({ type: 'login/autoLogin' });
    }
    if (token) {
      await dispatch({
        type: 'authority/getAuthApis'
      });
      updateUserInfo(token);
    }
  });

  const getTip = () => {
    if (autoLogining) return '自动登录中...';
    if (authApisLoading) return 'AuthApiLoading...';
    if (currentLoading) return '获取用户信息...';
    if (fetchPermissionsLoading) return '获取用户权限...';
    return '';
  };
  const loading = fetchPermissionsLoading || currentLoading || authApisLoading || autoLogining;
  const spinning = <LayoutLoading tip={getTip()}></LayoutLoading>;
  return <Fragment>{loading ? spinning : children}</Fragment>;
};

export default connect(({ login, loading }) => ({
  login,
  autoLogining: loading.effects['login/autoLogin'],
  authApisLoading: loading.effects['authority/getAuthApis'],
  currentLoading: loading.effects['user/fetchCurrent'],
  fetchPermissionsLoading: loading.effects['user/fetchPermissions']
}))(UserInfoLayout);
